//
//  SY_PaymentResultViewController.m
//  ChatDemo-UI2.0
//
//  Created by Sylar on 2017/1/4.
//  Copyright © 2017年 Sylar. All rights reserved.
//

#import "SY_PaymentResultViewController.h"
#import <AlipaySDK/AlipaySDK.h>
@interface SY_PaymentResultViewController ()<UITextViewDelegate>
@property (nonatomic, strong) NSDictionary *detailDic;

@end

@implementation SY_PaymentResultViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithImage:[UIImage imageWithOriginalName:@"back"] style:UIBarButtonItemStyleDone target:self action:@selector(backToRoot)];
    self.navigationItem.leftBarButtonItem = left;
    
    [self loadPaymentDetail];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(rePaymentResult:) name:@"RePaymentBySchool" object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}

#pragma mark - Method

- (void)backToRoot {
    
    [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:1] animated:YES];
}

- (void)loadPaymentDetail {
    
    NSMutableDictionary *parmaDic = [[NSMutableDictionary alloc]init];
    
    [parmaDic setObject:@"api_receiptinfo_toparent" forKey:@"method"];
    [parmaDic setObject:USERID forKey:@"userid"];
    [parmaDic setObject:self.payId forKey:@"payid"];
    
    [Utils get:nil parameters:parmaDic success:^(NSInteger recode, id jsonObject) {
        
        NSArray *dataArr = [jsonObject objectForKey:@"re_data"];
        
        if (dataArr != nil && dataArr.count > 0) {
            self.detailDic = [dataArr firstObject];
            
            [self creatView];
        }
 
    } failure:^(NSInteger recode, NSError *error) {
        
    }];
    
}

- (void)creatView {
    
    for (UIView *view in self.view.subviews) {
        [view removeFromSuperview];
    }
    UIImageView *resultImg = [[UIImageView alloc]initWithFrame:CGRectMake(SCREENWIDTH/2.0 - 57.5, 68, 115, 135)];
    [self.view addSubview:resultImg];
    
    UILabel *resultLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, resultImg.bottom, SCREENWIDTH, 20)];
    [resultLabel setTextAlignment:NSTextAlignmentCenter];
    [resultLabel setTextColor:colorFromHex(@"#3b3b3b")];
    //[resultLabel setFont:[UIFont systemFontOfSize:20]];
    [resultLabel setFont:[UIFont boldSystemFontOfSize:20]];
    [self.view addSubview:resultLabel];
    
    
    if ([[self.resultDic objectForKey:@"resultStatus"] isEqualToString:@"9000"]) {
        self.title = @"交费成功";
        [resultImg setImage:[UIImage imageNamed:@"payment_success_"]];
        [resultLabel setText:@"交费成功"];
        
        NSString *orderId = [NSString stringWithFormat:@"订单号:%@",[self.detailDic objectForKey:@"ordercode"]];
        
        UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake((SCREENWIDTH - orderId.length*14)/2.0, resultLabel.bottom+90, SCREENWIDTH, 14)];
        [label1 setFont:[UIFont systemFontOfSize:14]];
        [label1 setTextColor:colorFromHex(@"#3b3b3b")];
        [label1 setText:orderId];
        [self.view addSubview:label1];
        
        UILabel *label2 = [[UILabel alloc]initWithFrame:CGRectMake(label1.x, label1.bottom+6, SCREENWIDTH, 14)];
        [label2 setFont:[UIFont systemFontOfSize:14]];
        [label2 setTextColor:colorFromHex(@"#3b3b3b")];
        [label2 setText:[NSString stringWithFormat:@"交易号:%@",[self.detailDic objectForKey:@"paycode"]]];
        [self.view addSubview:label2];
        
        NSString *dateStr;
        if ([[self.detailDic objectForKey:@"paytime"] length] > 10) {
            dateStr = [[self.detailDic objectForKey:@"paytime"] substringToIndex:10];
        }
        
        UILabel *label3 = [[UILabel alloc]initWithFrame:CGRectMake(label1.x, label2.bottom+6, SCREENWIDTH, 14)];
        [label3 setFont:[UIFont systemFontOfSize:14]];
        [label3 setTextColor:colorFromHex(@"#3b3b3b")];
        [label3 setText:[NSString stringWithFormat:@"交易时间:%@",dateStr]];
        [self.view addSubview:label3];
        
    }else {
        [resultImg setImage:[UIImage imageNamed:@"payment_failure_"]];
        [resultLabel setText:@"交费失败"];
        self.title = @"交费失败";
        
        UILabel *label4 = [[UILabel alloc]initWithFrame:CGRectMake(90, resultImg.bottom+90, 76, 14)];
        [label4 setFont:[UIFont systemFontOfSize:15]];
        [label4 setTextColor:colorFromHex(@"#3b3b3b")];
        [label4 setText:@"失败原因:"];
        [self.view addSubview:label4];
        
        UITextView *failLabel = [[UITextView alloc]initWithFrame:CGRectMake(166, resultImg.bottom+80, SCREENWIDTH-256, 80)];
        failLabel.delegate = self;
        failLabel.editable = YES;
        failLabel.scrollEnabled = NO;
        [failLabel setFont:[UIFont systemFontOfSize:15]];
        [failLabel setTextColor:colorFromHex(@"#3b3b3b")];
        if ([[self.resultDic objectForKey:@"memo"] length] > 0) {
            [failLabel setText:[self.resultDic objectForKey:@"memo"]];
        }else {
            [failLabel setText:[self failCode:[[self.resultDic objectForKey:@"resultStatus"] integerValue]]];
        }
        [self.view addSubview:failLabel];
        
        
        UIButton *repayBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [repayBtn setFrame:CGRectMake(SCREENWIDTH/2.0 - 90, SCREENHEIGH-64-165, 180, 40)];
        repayBtn.layer.cornerRadius = 20.0;
        [repayBtn setTitleColor:colorFromHex(@"#ffffff") forState:(UIControlStateNormal)];
        [repayBtn setTitle:@"重新交费" forState:(UIControlStateNormal)];
        [repayBtn setBackgroundColor:colorFromHex(@"#39adff")];
        [repayBtn addTarget:self action:@selector(payAction) forControlEvents:(UIControlEventTouchUpInside)];
        [self.view addSubview:repayBtn];
    }
    
}

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
    
    return NO;
}
- (void)rePaymentResult:(NSNotification *)dict{
    
    self.resultDic = dict.userInfo;
    [self loadPaymentDetail];
}

- (NSString *)failCode:(NSInteger )resultStatus {
    
    NSString *resultStr;
    
    switch (resultStatus) {
        case 8000:
            resultStr = @"正在处理中，支付结果未知（有可能已经支付成功），请查询商户订单列表中订单的支付状态";
            break;
        case 4000:
            resultStr = @"订单支付失败";
            break;
        case 5000:
            resultStr = @"重复请求";
            break;
        case 6001:
            resultStr = @"用户中途取消";
            break;
        case 6002:
            resultStr = @"网络连接出错";
            break;
        case 6004:
            resultStr = @"支付结果未知（有可能已经支付成功），请查询商户订单列表中订单的支付状态";
            break;
        default:
            resultStr = @"其它支付错误";
            break;
    }
    
    return resultStr;
}


#pragma mark - Action

- (void)payAction {
    
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    [dict setObject:@"api_receipt_pay" forKey:@"method"];
    [dict setObject:USERID forKey:@"userid"];
    [dict setObject:self.payId forKey:@"payid"];
    [dict setObject:self.payType forKey:@"typeid"];
    
    [Utils noHUD_get:nil parameters:dict success:^(NSInteger recode, id jsonObject) {
        
        [self handleResultWithDic:jsonObject];
        
    } failure:^(NSInteger recode, NSError *error) {
        
    }];
}

/**处理接口返回结果*/
- (void)handleResultWithDic:(NSDictionary *)dict{
    
    //_dict = dict;
    
    int code = [[dict objectForKey:@"re_code"] intValue];
    NSString *re_info = [dict objectForKey:@"re_info"];
    
    if (code == 0) {
        
        [[AlipaySDK defaultService] payOrder:[[dict objectForKey:@"re_data"] objectForKey:@"paystr"] fromScheme:@"youer" callback:^(NSDictionary *resultDic) { //网页支付会走这个回调
            
            //int resultStatus = [[resultDic objectForKey:@"resultStatus"] intValue];
            
            SY_PaymentResultViewController *resultVC = [[SY_PaymentResultViewController alloc]init];
            resultVC.resultDic = resultDic;
            resultVC.payId = self.payId;
            resultVC.payType = self.payType;
            [self.navigationController pushViewController:resultVC animated:YES];

        }];
        
    }else{
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self showHint:re_info];
        });
        
    }
}



@end
